package com.example.algorithm.test;

import org.junit.Test;

/**
 * 统计素数个数
 * @auther lijiewei
 * @date 2024-03-07 20:25
 */
public class PrimeNumber {

    /** 暴力循环. */
    public int force(int n) {
        int count = 0;
        for (int i = 2; i < n; i++) {
            count += isPrime(i) ? 1 : 0;
        }
        return count;
    }

    private boolean isPrime(int x) {
        for (int i = 2; i * i <= x; i++) {
            if (x % i == 0) {
                return false;
            }
        }
        return true;
    }

    @Test
    public void forceTest() throws Exception{
        System.out.println(force(100));
    }

    /** 埃筛法. */
    private int eratosthenes(int n) {
        int count = 0;
        //合数数组，true 为合数（非素数），false 为素数
        boolean[] compositeNumber = new boolean[n];
        //i 从2 开始，因为 0 和 1 不判断
        for (int i = 2; i < n; i++) {
            if (!compositeNumber[i]) {
                count++;
                /*for (int j = 2 * i; j < n; j += i) {
                    compositeNumber[j] = true;
                }
                2*2 2*3 2*5 2*6
                3*2 3*3 3*5
                4*2 4*3 4*5
                5*2 5*3 5*5
                6*2
                */
                for (int j = i * i; j < n; j += i) {
                    compositeNumber[j] = true;
                }
            }
        }
        return count;
    }

    @Test
    public void eratosthenesTest() throws Exception{
        System.out.println(eratosthenes(100));
    }
}
